﻿<#
.SYNOPSIS

Configures the local Administrator account.
#>

Set-StrictMode -Version "2.0"

# Gets the name of the local Administrator account, based on its well-known SID.
function Get-LocalAdminName
{
    [string]$returnValue = [string]::Empty

    [System.Text.RegularExpressions.Regex]$adminSidRegEx = New-Object System.Text.RegularExpressions.Regex("^S-1-5-.+-500$")
    [System.DirectoryServices.DirectoryEntry]$localMachine = New-Object System.DirectoryServices.DirectoryEntry([string]::Format("WinNT://{0}", [System.Environment]::MachineName))
    foreach ($user in $localMachine.Children)
    {
        if ([string]::Compare($user.SchemaClassName, "User", $true) -eq 0)
        {
            if ($user.Properties["objectSid"] -ne $null)
            {
                for ([int]$i = 0; $i -lt $user.Properties["objectSid"].Count; $i++)
                {
                    [Byte[]]$sidBytes = [Byte[]]$user.Properties["objectSid"][$i]
                    [System.Security.Principal.SecurityIdentifier]$sid = New-Object System.Security.Principal.SecurityIdentifier($sidBytes, 0)
                    if ($adminSidRegEx.IsMatch($sid.Value))
                    {
                        $returnValue = $user.Name
                    }
                }
            }
        }
    }
    return $returnValue
}

# Get the name of the local Administrator account.
[string]$localAdminName = Get-LocalAdminName
Write-Host ("The local administrator account is named {0}." -f $localAdminName)

# Get a reference to the local Administrator account.
[string]$objectPath = [string]::Format("WinNT://{0}/{1},user", [System.Environment]::MachineName, (Get-LocalAdminName))
$adminDirectoryEntry = New-Object System.DirectoryServices.DirectoryEntry -ArgumentList $objectPath

# Clear the user's password.
$adminDirectoryEntry.Invoke("SetPassword", ([string]::Empty))
$adminDirectoryEntry.CommitChanges()	

$adminDirectoryEntry.Dispose | Out-Null

# Return a success error code.
exit 0